package com.zw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zw.dto.ApplyRecordPagesDto;
import com.zw.dto.PermApplyDto;
import com.zw.dto.PermAuditDto;
import com.zw.entity.PermissionApplyRecord;
import com.zw.entity.SysUserRole;
import com.zw.mapper.PermissionApplyRecordMapper;
import com.zw.mapper.SysUserRoleMapper;
import com.zw.service.PermissionApplyRecordService;
import com.zw.utils.CopyUtils;
import com.zw.utils.SecurityUtils;
import com.zw.vo.ApplyRecordPagesVO;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * (PermissionApplyRecord)表服务实现类
 *
 * @author makejava
 * @since 2025-03-25 23:41:46
 */
@Service("permissionApplyRecordService")
@Slf4j
public class PermissionApplyRecordServiceImpl
        extends ServiceImpl<PermissionApplyRecordMapper, PermissionApplyRecord>
        implements PermissionApplyRecordService {
    @Resource
    private PermissionApplyRecordMapper permissionApplyRecordMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 权限申请
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean permApply(PermApplyDto dto) {
        if (Objects.isNull(dto)) {
            throw new RuntimeException("请求参数错误！");
        }
        PermissionApplyRecord applyRecord = permissionApplyRecordMapper.selectOne(new QueryWrapper<PermissionApplyRecord>().lambda()
                .eq(PermissionApplyRecord::getApplyRoleId, dto.getApplyRoleId())
                .eq(PermissionApplyRecord::getApplyUserId, SecurityUtils.getUserId())
                .eq(PermissionApplyRecord::getAuditStatus, 0));
        if (Objects.nonNull(applyRecord)){
            throw new RuntimeException("已申请该权限，等待管理员审批，无需再次申请！");
        }
        //查询是否已经拥有改权限
        SysUserRole userRole = sysUserRoleMapper.selectOne(new QueryWrapper<SysUserRole>().lambda()
                .eq(SysUserRole::getUserId, SecurityUtils.getUserId())
                .eq(SysUserRole::getRoleId, dto.getApplyRoleId()));
        if (Objects.nonNull(userRole)) {
            throw new RuntimeException("已拥有该权限，不能重复申请！");
        }
        PermissionApplyRecord record = CopyUtils.copyObj(dto, PermissionApplyRecord.class);
        record.setApplyUserId(SecurityUtils.getUserId());
        record.setCreateBy(SecurityUtils.getEmail());
        record.setCreateTime(new Date());
        int insert = permissionApplyRecordMapper.insert(record);
        if (insert > 0) {
            log.info("[{}],申请[{}]权限成功！", SecurityUtils.getEmail(), dto.getApplyRoleId());
            return true;
        }
        return false;
    }

    /**
     * 权限审核列表分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageInfo<ApplyRecordPagesVO> applyRecordPages(ApplyRecordPagesDto dto) {

        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<ApplyRecordPagesVO> list = permissionApplyRecordMapper.applyRecordPages(dto);
        return new PageInfo<>(list);
    }

    /**
     * 权限审核
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean permAudit(PermAuditDto dto) {
        if (Objects.isNull(dto)) {
            throw new RuntimeException("请求参数异常！");
        }
        PermissionApplyRecord record = permissionApplyRecordMapper.selectById(dto.getApplyId());
        if (Objects.isNull(record)) {
            throw new RuntimeException("审核数据不存在！");
        }
        if (record.getAuditStatus() != 0) {
            throw new RuntimeException("数据已审核，无法二次审核！");
        }
        PermissionApplyRecord auditInfo = new PermissionApplyRecord();
        auditInfo.setApplyId(dto.getApplyId());
        if (dto.getAuditStatus() == 0) {
            auditInfo.setAuditStatus(1);
        } else {
            auditInfo.setAuditStatus(2);
        }
        auditInfo.setUpdateBy(SecurityUtils.getEmail());
        auditInfo.setUpdateTime(new Date());
        int result = permissionApplyRecordMapper.updateById(auditInfo);
        if (result > 0) {
            log.info("权限审核成功！");
            if (dto.getAuditStatus() == 0) {
                log.info("该用户：{}申请角色被审批通过，需要删除所有角色",record.getApplyUserId());
                //审核结果是通过，则同时更新用户角色关联表信息，删除该用户其他权限
                sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda()
                        .eq(SysUserRole::getUserId, record.getApplyUserId()));
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(record.getApplyUserId());
                userRole.setRoleId(record.getApplyRoleId());
                sysUserRoleMapper.insertOne(userRole);
            }
            return true;
        }
        return false;
    }
}
